package cn.hesion.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioTest {
    public static void main(String[] args) {
        try {
            selector();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void selector() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();


        
        ssc.configureBlocking(false);//设置为非阻塞方式
        ssc.socket().bind(new InetSocketAddress(8080));
        ssc.register(selector, SelectionKey.OP_ACCEPT);//注册监听的时间
        while(true){
            //取得所有key的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while(it.hasNext()){
                SelectionKey key = it.next();
                if((key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){
                    ServerSocketChannel sschannel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = sschannel.accept(); //接受服务器的请求
                    sc.configureBlocking(false);
                    sc.register(selector,SelectionKey.OP_READ);
                    it.remove();
                }else if((key.readyOps() & SelectionKey.OP_READ)==SelectionKey.OP_READ){
                    SocketChannel sc = (SocketChannel) key.channel();
                    while(true){
                        buffer.clear();
                        int read = sc.read(buffer);// 获取数据
                        if(read <=0){
                            break;
                        }
                        buffer.flip();
                    }
                    it.remove();
                }
            }
        }

    }
}
